package com.javafactroy.kunlong.bip.icp.context.connpool.dxpftp;

import com.javafactroy.kunlong.bip.icp.common.config.BipConfig;
import com.javafactroy.kunlong.bip.icp.ftpclient.dxp.DxpFtpTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
@Scope("singleton")
public class DxpFtpTemplateFactory extends BasePooledObjectFactory<DxpFtpTemplate> {
    @Autowired
    BipConfig bipConfig;

    public DxpFtpTemplateFactory() {

    }

    /**
     * 新建对象
     */
    @Override
    public DxpFtpTemplate create() throws Exception {
        DxpFtpTemplate ftpTemplate = new DxpFtpTemplate();
        ftpTemplate.setBipConfig(bipConfig);
        ftpTemplate.init();
        return ftpTemplate;
    }

    @Override
    public PooledObject<DxpFtpTemplate> wrap(DxpFtpTemplate DxpFtpTemplate) {
        return new DefaultPooledObject<DxpFtpTemplate>(DxpFtpTemplate);
    }

    /**
     * 销毁对象
     */
    @Override
    public void destroyObject(PooledObject<DxpFtpTemplate> p) throws Exception {
        DxpFtpTemplate ftpClient = p.getObject();
        ftpClient.close();
        super.destroyObject(p);
    }

    /**
     * 验证对象
     */
    @Override
    public boolean validateObject(PooledObject<DxpFtpTemplate> p) {
        DxpFtpTemplate ftpClient = p.getObject();
        boolean connect = false;
        try {
            connect = ftpClient.getFtp().getClient().sendNoOp();
            if (connect) {
                //ftpClient.getFtp().getClient().changeWorkingDirectory();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return connect;
    }


}

 
